package com.fellansoft.moviescollection.activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.*;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.*;
import com.fellansoft.moviescollection.R;
import com.fellansoft.moviescollection.business.BusinessConstants;
import com.fellansoft.moviescollection.business.DataManager;
import com.fellansoft.moviescollection.data.Movie;
import com.fellansoft.moviescollection.utils.ActivityUtils;
import com.fellansoft.moviescollection.utils.ApplicationVariables;

import java.text.DateFormat;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: Naty      ->Naty
 * Date: 6/8/12
 * Time: 9:40 PM
 * To change this template use File | Settings | File Templates.
 */
public class EditMovie extends Activity{
    /**
     * The movie which is being edited
     */
    public static Movie myMovie;
    /**
     * Text view containg the title of the movie
     */
    private TextView titleView;
    /**
     * Edit text with the release date of the movie
     */
    private EditText dateEditText;
    /**
     * Button starting the date picker
     */
    private Button selectDateButton;
    /**
     * Button opening a multiple choice list for the categories of the movie
     */
    private Button selectCategoriesButton;
    /**
     * Button starting an activity for managing URI list
     */
    private Button addPictureButton;
    /**
     * Button for aborting the editing of the movie
     */
    private Button cancelButton;
    /**
     * Button for saving the changes which where made
     */
    private Button saveButton;
    /**
     * Constant for opening a dialog with the date picker
     */
    static final int DATE_DIALOG_ID = 999;
    /**
     * Integer for storing the current year
     */
    private int year=2000;
    /**
     * Integer for storing the current month
     */
    private int month=1;
    /**
     * Integer for storing the current day
     */
    private int day=1;
    /**
     * List containg all the categories
     */
    protected CharSequence[] categories;
    /**
     * Edit text for the description of a movie
     */
    private EditText descriptionEditText;
    /**
     * Array of boolean values for the selected categories
     */
    protected boolean[] categoriesSelection;
    /**
     * Checkbox for watchlist option
     */
    private CheckBox watchlistCheckbox;
    /**
     * Checkbox for making a movie favorite
     */
    private CheckBox favouriteCheckbox;
    /**
     * Rating bar showing a own movie rate based on a float value
     */
    private RatingBar ratingBar;
    /**
     * Constant for opening a multiple choice menu for categories
     */
    static final int CATEG_DIALOG_ID = 666;
    /**
     * Current context
     */
    private Context context;
    /**
     * Intent filter for the intents sent when the book was updated successfully
     */
    private IntentFilter updateMovieSuccessIntentFilter;

    /**
     * Intent filter for the intents sent when the book was not updated successfully
     */
    private IntentFilter updateMovieErrorIntentFilter;

    /**
     * Receiver for the intents sent when the book was updated successfully to database
     */
    private BroadcastReceiver updateMovieSuccessReceiver;

    /**
     * Receiver for the intents sent when there was a problem saving the new book to database
     */
    private BroadcastReceiver updateMovieErrorReceiver;

    /**
     * Current selected date
     * 
     */
    private static Date currentSelectedDate=new Date();
    private static Uri cover;
    private static List<Uri> listUri;
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        context= ApplicationVariables.getApplicationContext();
        setTheme(android.R.style.Theme_Holo);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.addmovie);
        myMovie= ViewMovie.m;

        titleView=(TextView)findViewById(R.id.addTitleEditText);
        titleView.setText(myMovie.getTitle());
        dateEditText=(EditText)findViewById(R.id.dateEditText);
        Log.d("DATE", Integer.toString(myMovie.getReleaseDate().getYear()));
        Log.d("DATE", Integer.toString(myMovie.getReleaseDate().getMonth()));
        Log.d("DATE",Integer.toString(myMovie.getReleaseDate().getDay()));
        dateEditText.setText(DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault()).format(myMovie.getReleaseDate()));
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(myMovie.getReleaseDate());

        //date selection
        year = myMovie.getReleaseDate().getYear()+1900;
        day=calendar.get(Calendar.DAY_OF_MONTH);
        month=calendar.get(Calendar.MONTH);

        currentSelectedDate.setTime(calendar.getTimeInMillis());
        selectDateButton=(Button)findViewById(R.id.datePickerButton);
        selectDateButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });
        
        //categories selection
      //  categoriesSelection=myMovie.getCategories();
        categories = getResources().getStringArray(R.array.Categories);
        categoriesSelection = new boolean[categories.length ];

        ///naty - need to add categories
        categoriesSelection=myMovie.getCategories();
         selectCategoriesButton=(Button)findViewById(R.id.selectCategory)   ;
        selectCategoriesButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                showDialog(CATEG_DIALOG_ID);
            }
        });

        //description
        descriptionEditText=(EditText)findViewById(R.id.addDescription);
        descriptionEditText.setText(myMovie.getDescription());

        //rest
        ratingBar=(RatingBar)findViewById(R.id.rating);
        ratingBar.setRating(myMovie.getOwnRating());
       /* ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {

            public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
                Toast.makeText(getApplicationContext(), ""+ratingBar.getRating(), Toast.LENGTH_LONG).show();
            }
        });    */
        watchlistCheckbox=(CheckBox)findViewById(R.id.watchCheckB);
        favouriteCheckbox=(CheckBox)findViewById(R.id.favoriteCheckB);
        watchlistCheckbox.setChecked(myMovie.getWatchList());
        favouriteCheckbox.setChecked(myMovie.getFavorite());
        cancelButton=(Button)findViewById(R.id.cancelButton);
        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        saveButton=(Button)findViewById(R.id.saveMovieButton);
        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Toast.makeText(getApplicationContext(),"Save", Toast.LENGTH_LONG).show();
                if (updateMovieSuccessIntentFilter == null)
                    updateMovieSuccessIntentFilter = new IntentFilter(BusinessConstants.BC_MOVIES_UPDATED_SUCCESSFULLY);
                if (updateMovieSuccessReceiver == null)
                    updateMovieSuccessReceiver = new BroadcastReceiver() {
                        @Override
                        public void onReceive(Context localContext, Intent intent) {
                            try {
                                context.unregisterReceiver(updateMovieSuccessReceiver);
                            } catch(IllegalArgumentException e) {
                                e.printStackTrace();
                            }

                            //Show a message on the screen
                            Toast.makeText(EditMovie.this,EditMovie.this.getResources().getString(R.string.update_success_message),Toast.LENGTH_SHORT).show();
                            EditMovie.this.setResult(Activity.RESULT_OK);
                            ViewMovie.m=DataManager.getInstance().getMovieById(myMovie.getId());
                            ActivityUtils.hideProgressDialog(EditMovie.this);
                            finish();
                        }
                    };
                context.registerReceiver(updateMovieSuccessReceiver, updateMovieSuccessIntentFilter);

                if (updateMovieErrorIntentFilter == null)
                    updateMovieErrorIntentFilter = new IntentFilter(BusinessConstants.BC_MOVIES_UPDATED_ERROR);
                if (updateMovieErrorReceiver == null)
                    updateMovieErrorReceiver = new BroadcastReceiver() {
                        @Override
                        public void onReceive(Context localContext, Intent intent) {
                            try {
                                context.unregisterReceiver(updateMovieErrorReceiver);
                            } catch(IllegalArgumentException e) {
                                e.printStackTrace();
                            }
                            //Hide the spinning dialog
                            ActivityUtils.hideProgressDialog(EditMovie.this);

                            //Show a message on the screen
                            Toast.makeText(EditMovie.this,EditMovie.this.getResources().getString(R.string.update_error_message),Toast.LENGTH_SHORT).show();
                        }
                    };
                context.registerReceiver(updateMovieErrorReceiver,updateMovieErrorIntentFilter);

                    //remake uri list
                     listUri=myMovie.getPhotos();
                     cover=myMovie.getCoverPhoto();
                    if(PictureControl.uriList!=null)
                    {
                        listUri=PictureControl.uriList;
                        cover=listUri.get(0);
                    }

                ActivityUtils.showProgressDialog(EditMovie.this);

                DataManager.getInstance().requestUpdateMovie(myMovie.getId(), titleView.getText().toString(), // title
                        currentSelectedDate, //releaseDate
                        descriptionEditText.getText().toString(), //description
                        "", // director
                        categoriesSelection, // categories
                        watchlistCheckbox.isChecked(), //watchlist
                        favouriteCheckbox.isChecked(), //favourite
                        ratingBar.getRating(), //ownRating
                             cover,
                             listUri);


            }
        });
        

        addPictureButton=(Button)findViewById(R.id.managePictures);
        addPictureButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                //DataManager.getInstance().getMovieById(Long.valueOf(1));
                //Intent intent=new Intent(AddMovie.this,PictureControl.class);
                // startActivity(intent);
                Intent intent=new Intent(EditMovie.this,PictureControl.class);
                intent.putExtra("ADDMOVIE",0);
                startActivity(intent);
            }
        });

    }
        @Override
        protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DATE_DIALOG_ID:
                //creates the DatePicker with the datePickerListener and initial values: year,month,date
                return new DatePickerDialog(this, datePickerListener, year, month, day);
            case CATEG_DIALOG_ID:
                //creates the DatePicker with the datePickerListener and initial values: year,month,date
                return
                        new AlertDialog.Builder( this )
                                .setTitle( R.string.categories )
                                .setMultiChoiceItems(categories, categoriesSelection , new EditMovie.DialogSelectionClickHandler() )
                                .setPositiveButton(R.string.save, new EditMovie.DialogButtonClickHandler())
                                .create();
        }
        return null;
    }
        // Listener for Date Picker
        private DatePickerDialog.OnDateSetListener datePickerListener
                = new DatePickerDialog.OnDateSetListener() {

            // when dialog box is closed, below method will be called.
            public void onDateSet(DatePicker view, int selectedYear,
                                  int selectedMonth, int selectedDay) {
                Date d = new Date(selectedYear-1900,selectedMonth,selectedDay);
                dateEditText.setText(DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault()).format(d));
                currentSelectedDate=d;
                // set selected date into datepicker also
                //  dpResult.init(year, month, day, null);
            }
        };
    public class DialogButtonClickHandler implements DialogInterface.OnClickListener
    {
        public void onClick( DialogInterface dialog, int clicked )
        {
            switch( clicked )
            {
                case DialogInterface.BUTTON_POSITIVE:
                    // do nothing
                    //Toast.makeText(getApplicationContext(),categoriesSelection[0]==true?"true":"false",Toast.LENGTH_SHORT).show();
                    //categoriesSelection = ((AlertDialog)dialog).getListView().;
                    //printSelectedCategories();
                    break;
            }
        }
    }
    public class DialogSelectionClickHandler implements DialogInterface.OnMultiChoiceClickListener
    {
        public void onClick( DialogInterface dialog, int clicked, boolean selected )
        {

            //change is made in the list

            /*public void onClick(DialogInterface dialog, int which, boolean isChecked) {
            if(isChecked)
                selectedColours.add(colours[which]);
            else
                selectedColours.remove(colours[which]);

            onChangeSelectedColours();
        }      */
        }

    }

}
